package cn.iocoder.yudao.module.system.controller.admin.portal;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.rsa.RsaUtils;
import cn.iocoder.yudao.module.system.controller.admin.portal.vo.PortalUserPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.portal.vo.PortalUserRespVO;
import cn.iocoder.yudao.module.system.controller.admin.portal.vo.PortalUserSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.portal.PortalUserDO;
import cn.iocoder.yudao.module.system.service.portal.PortalUserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 门户网站用户")
@RestController
@RequestMapping("/portalUser")
@Validated
public class PortalUserController {

    @Resource
    private PortalUserService userService;

    @Resource
    private RsaUtils rsaUtils;

    @PostMapping("/create")
    @Operation(summary = "创建门户网站用户")
    public CommonResult<Long> createUser(@Valid @RequestBody PortalUserSaveReqVO createReqVO) {
        try {
            // 对前端加密的密码进行解密
            if (createReqVO.getPassword() != null && !createReqVO.getPassword().isEmpty()) {
                String decryptedPassword = rsaUtils.decryptByPrivateKey(createReqVO.getPassword());
                createReqVO.setPassword(decryptedPassword);
            }
        } catch (Exception e) {
            throw new ServiceException("密码解密失败：" + e.getMessage());
        }
        return success(userService.createUser(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新门户网站用户")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody PortalUserSaveReqVO updateReqVO) {
        userService.updateUser(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除门户网站用户")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除门户网站用户")
    public CommonResult<Boolean> deleteUserList(@RequestParam("ids") List<Long> ids) {
        userService.deleteUserListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得门户网站用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<PortalUserRespVO> getUser(@RequestParam("id") Long id) {
        PortalUserDO user = userService.getUser(id);
        return success(BeanUtils.toBean(user, PortalUserRespVO.class));
    }

    /**
     * 获取科信处审核人员列表
     * @return
     */
    @GetMapping("/portal/get-kx-list")
    @Operation(summary = "获取科信处审核人员列表")
    public CommonResult<List<PortalUserRespVO>> getKxList() {
        List<PortalUserDO> list = userService.getKxList();
        return success(BeanUtils.toBean(list, PortalUserRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得门户网站用户分页")
    public CommonResult<PageResult<PortalUserRespVO>> getUserPage(@Valid PortalUserPageReqVO pageReqVO) {
        PageResult<PortalUserDO> pageResult = userService.getUserPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, PortalUserRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出门户网站用户 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportUserExcel(@Valid PortalUserPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PortalUserDO> list = userService.getUserPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "门户网站用户.xls", "数据", PortalUserRespVO.class,
                        BeanUtils.toBean(list, PortalUserRespVO.class));
    }
    /**
     * 修改密码
     */
    @PutMapping("/update-password")
    @Operation(summary = "修改密码")
    public CommonResult<Boolean> updateUserPassword(@Valid @RequestBody PortalUserSaveReqVO reqVO) {
        try {
            // 解密密码
            if (reqVO.getPassword() != null && !reqVO.getPassword().isEmpty()) {
                String decryptedPassword = rsaUtils.decryptByPrivateKey(reqVO.getPassword());
                userService.updateUserPassword(reqVO.getId(), decryptedPassword);
            }
        } catch (Exception e) {
            throw new ServiceException("密码解密失败：" + e.getMessage());
        }
        return success(true);
    }
    /**
     * 获取全部用户列表（部门）
     */
    @GetMapping("/get-all-list")
    @Operation(summary = "获取全部用户列表（部门）")
    public CommonResult<List<PortalUserRespVO>> getAllUserList() {
        return success(BeanUtils.toBean(userService.getUserList(), PortalUserRespVO.class));
    }
    /**
     * 获取全部用户列表（部门）
     */
    @GetMapping("/portal/get-all-list")
    @Operation(summary = "获取全部用户列表（部门）")
    public CommonResult<List<PortalUserRespVO>> getPortalAllUserList() {
        return success(BeanUtils.toBean(userService.getUserList(), PortalUserRespVO.class));
    }
}